﻿
using HBase;
using System;
using System.Collections.Generic;

namespace hCommand {
    public class Transfer :ZtTask {

        private IWCSServer wcsServer = WMSDalFactray.getDal<IWCSServer>();
        ICoreTaskServer taskServer = WMSDalFactray.getDal<ICoreTaskServer>();
        public Transfer() {
            time = 500;
        }

        //缓存 CoreWhLoc BStn  BStnRelation CoreTaskParam，node
        protected override bool onlyOneTimeAsync() {
            base.onlyOneTimeAsync();
            MyCache.addOver(taskServer.GetAll<CoreWhLoc>());
            MyCache.addOver(wcsServer.GetPhysicalStns());
            MyCache.addOver(wcsServer.GetPhysicalStnRelation());

            List<BStn> physicalStns = MyCache.getList<BStn>();
            foreach( BStn stn in physicalStns ) {

                Node node = PathFacade.getConfig(stn.eid);
                if( node == null ) {
                    node = new Node(stn);
                    MyCache.addOver(node);
                } else {
                    fileAll("eid{0} 重复" ,stn.eid);
                }
                
            }

            List<BStnRelation> stnRelations = MyCache.getList<BStnRelation>();
            foreach( BStnRelation physical in stnRelations ) {
                PathFacade.addQueue(physical);
            }

            List<CoreTaskParam> pars = taskServer.GetAll<CoreTaskParam>(String.Format(" and status>={0} and status< {1}" ,( int ) CoreTaskParamStatus.下发完成 ,( int ) CoreTaskParamStatus.执行完成));
            MyCache.addOver(pars);

            List<CoreTaskParam> paramList = MyCache.query<CoreTaskParam>((a) => {
                return a.uploaded == 0;
            });
            foreach( CoreTaskParam p in paramList ) {
                CoreTask complete = taskServer.getById<CoreTask>(p.taskId);
                PathFacade.splitParam(p ,complete);
            }



            return true;
        }
        public override bool excute() {
           
            List<CoreTaskParam> list = taskServer.getWorkingTaskParam();
            if( null == list || list.Count == 0 )
                return true;
            foreach( CoreTaskParam param in list ) {
                oneParam(param ,list);
                return true;
            }
            return true;
        }

        void oneParam(CoreTaskParam param ,List<CoreTaskParam> list) {

            for( int i = 0;i < list.Count;i++ ) {
                CoreTaskParam realyParam = list[i];
                if( param.relyParamId == realyParam.id && realyParam.status < ( int ) CoreTaskParamStatus.下发完成 ) {
                    return;
                }
            }

            MyCache.addOver(param);
            bool split = taskServer.splitParam(param.id);

            if( split ) {
                taskServer.updateTaskParamStatus(param.id ,CoreTaskParamStatus.下发完成);
            }
        }




    }
}
